<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>DeepSeek 聊天演示</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* 原有样式保持不变 */
        body {
            font-family: Arial, sans-serif;
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
        }

        #chat-container {
            height: 600px;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow-y: auto;
            padding: 15px;
            margin-bottom: 15px;
            background: #f9f9f9;
        }

        .message {
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 5px;
            max-width: 80%;
        }

        .user-message {
            background: #e3f2fd;
            margin-left: auto;
        }

        .bot-message {
            background: #f1f1f1;
            margin-right: auto;
        }

        #input-area {
            display: flex;
            gap: 10px;
        }

        #question-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            padding: 10px 20px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:disabled {
            background: #cccccc;
        }

        .status {
            color: #666;
            margin-bottom: 10px;
        }

        /* Markdown 渲染样式 */
        .bot-message pre {
            background: #f0f0f0;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }

        .bot-message code {
            font-family: 'Courier New', monospace;
            background: #f0f0f0;
            padding: 2px 4px;
            border-radius: 3px;
        }

        .bot-message blockquote {
            border-left: 3px solid #ccc;
            padding-left: 10px;
            margin-left: 0;
            color: #555;
        }

        .bot-message table {
            border-collapse: collapse;
            width: 100%;
        }

        .bot-message th,
        .bot-message td {
            border: 1px solid #ddd;
            padding: 8px;
        }

        .bot-message th {
            background: #f2f2f2;
        }

        /* Markdown 渲染样式 */
        .bot-message pre {
            background: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }

        .bot-message code {
            font-family: 'Courier New', monospace;
            background: #f5f5f5;
            padding: 2px 4px;
            border-radius: 3px;
        }

        .bot-message blockquote {
            border-left: 3px solid #ddd;
            padding-left: 10px;
            margin-left: 0;
            color: #666;
        }
    </style>
</head>

<body>
    <h1>DeepSeek 聊天演示</h1>
    <div class="status" id="connection-status">连接状态: 未连接</div>
    <div id="chat-container"></div>
    <div id="input-area">
        <input type="text" id="question-input" placeholder="输入您的问题...">
        <button id="send-button" disabled>发送</button>
    </div>

    <!-- 引入SockJS和STOMP库 -->
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <!-- 引入 marked.js 解析 Markdown -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

    <script>
        // 生成唯一会话ID
        function generateSessionId() {
            return 'session-' + Math.random().toString(36).substr(2, 9);
        }

        // DOM元素
        const chatContainer = document.getElementById('chat-container');
        const questionInput = document.getElementById('question-input');
        const sendButton = document.getElementById('send-button');
        const connectionStatus = document.getElementById('connection-status');

        // WebSocket变量
        let stompClient = null;
        let sessionId = generateSessionId();
        let currentBotMessage = null;
        let markdownBuffer = ""; // 存储完整的 Markdown 文本

        const token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyeSIsImxvZ2luX3VzZXJfa2V5IjoiYjcxNGYyZmEtNmYwNy00ZWRlLTg5MjItNTQ1NWIyMTgwNmFmIn0.BpqRjL6DRJG91lpoFRtCkJg8SUwf_kuXNyvE6ECGpZlauzPUd4t3trkkzDclE5ZcSvY3CcFFRPcEG0_y6ddr2g"

        // 连接WebSocket
        function connect() {
            connectionStatus.textContent = '连接状态: 连接中...';
            const socket = new SockJS(`http://localhost:8080/ws?access_token=${token}`, null, {
                transports: ['xhr-streaming', 'xhr-polling', 'websocket'],
                withCredentials: true
            });

            stompClient = Stomp.over(socket);
            stompClient.debug = null; // 关闭调试日志

            stompClient.connect({}, function (frame) {
                connectionStatus.textContent = '连接状态: 已连接';
                sendButton.disabled = false;

                // 订阅响应主题
                const topic = `/topic/chat.stream/${sessionId}`;
                stompClient.subscribe(topic, function (response) {
                    const data = JSON.parse(response.body);
                    handleStreamResponse(data);
                });

            }, function (error) {
                connectionStatus.textContent = '连接状态: 连接失败';
                console.error('连接错误:', error);
                setTimeout(connect, 5000); // 5秒后重连
            });
        }

        // 处理流式响应
        function handleStreamResponse(response) {
            if (response.isEnd) {
                currentBotMessage = null;
                markdownBuffer = ""; // 清空缓存
                sendButton.disabled = false;
            } else {
                if (!currentBotMessage) {
                    currentBotMessage = document.createElement('div');
                    currentBotMessage.className = 'message bot-message';
                    chatContainer.appendChild(currentBotMessage);
                }

                // 增量更新 Markdown 内容
                markdownBuffer += response.content;
                // 使用 marked.js 解析为 HTML
                currentBotMessage.innerHTML = marked.parse(markdownBuffer);
                scrollToBottom();
            }
        }

        // 发送问题
        function sendQuestion() {
            const question = questionInput.value.trim();
            if (!question || !stompClient || !stompClient.connected) return;

            // 重置 markdownBuffer
            markdownBuffer = "";

            // 添加用户消息
            const userMessage = document.createElement('div');
            userMessage.className = 'message user-message';
            userMessage.textContent = question;
            chatContainer.appendChild(userMessage);

            // 添加初始机器人消息
            currentBotMessage = document.createElement('div');
            currentBotMessage.className = 'message bot-message';
            currentBotMessage.innerHTML = marked.parse("正在思考...");
            chatContainer.appendChild(currentBotMessage);

            // 发送请求
            stompClient.send("/app/chat.stream", {}, JSON.stringify({
                sessionId: sessionId,
                role: "智能问答助手",
                question: question,
                extraInfo: ""
            }));

            questionInput.value = '';
            sendButton.disabled = true;
            scrollToBottom();
        }

        // 滚动到底部
        function scrollToBottom() {
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 事件监听
        sendButton.addEventListener('click', sendQuestion);
        questionInput.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') sendQuestion();
        });

        // 初始化连接
        connect();
    </script>
</body>

</html>